﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ClientWinPhone.Resources;

using Microsoft.AspNet.SignalR.Client;
using System.Threading.Tasks;

namespace ClientWinPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        HubConnection hubConnection;
        IHubProxy hubProxy;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            hubConnection = new HubConnection("http://localhost:30526/signalr/hubs");
            hubProxy = hubConnection.CreateHubProxy("HelloWorld");

            InitializeConnection();
        }

        private void Connected()
        {
            this.Dispatcher.BeginInvoke(() => MessageBox.Show("User baru bergabung."));
        }

        private async Task Show(string user, string pesan)
        {
            this.Dispatcher.BeginInvoke(() => ListBox_Chat.Items.Add(user + " : " + pesan));
        }

        private async Task InitializeConnection()
        {
            hubProxy.On("connected", Connected);
            hubProxy.On<string, string>("show", (user, pesan) => Show(user, pesan));
            await hubConnection.Start();
        }

        private void ApplicationBarIconButton_Send_Click(object sender, EventArgs e)
        {
            SendMassage("WP User", TextBox_Message.Text);
        }

        private async Task SendMassage(string user, string pesan)
        {
            await hubProxy.Invoke("Send", user, pesan);
            TextBox_Message.Text = String.Empty;
        }
    }
}